using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Autofac;
using DayDayUp.Core.DependencyManagement;

namespace DayDayUp.Core
{
    public class DmsEngine : IEngine
    {


        //private ContainerManager _containerManager;


        //public ContainerManager ContainerManager
        //{
        //    get { return _containerManager; }
        //}

        public static IContainer container;

        public DmsEngine()
        {
          

        }
     

        public IContainer Container()
        {
            return container ;
        }

        public void Initialize(IContainer containerParameter)
        {
            container = containerParameter;
        }

        public T Resolve<T>() where T : class
        {
            try
            {
                return DependencyResolver.Current.GetService<T>();
                //
            }
            catch (Exception e)
            {
                try
                {
                    
                    return AutofacRequestLifetimeHttpModule.GetLifetimeScope(container, null).Resolve<T>();
                }
                catch (Exception ex)
                {
                    
                }
            }
            return container.Resolve<T>();
        }

        public T[] ResolveAll<T>()
        {

            return DependencyResolver.Current.GetService<IEnumerable<T>>().ToArray();
            //return
            //    AutofacRequestLifetimeHttpModule.GetLifetimeScope(container, null).Resolve<IEnumerable<T>>().ToArray();

        }

        public T ResolveNamed<T>(string name) where T : class
        {
            try
            {
                return AutofacRequestLifetimeHttpModule.GetLifetimeScope(container, null).ResolveNamed<T>(name);
            }
            catch (Exception e)
            {

            }
            return container.ResolveNamed<T>(name);
        }

        public object Resolve(Type type)
        {
            //try
            //{
            //    return AutofacRequestLifetimeHttpModule.GetLifetimeScope(container, null).Resolve(type);
            //}
            //catch (Exception e)
            //{

            //}

            return container.Resolve(type);
        }
        public bool TryResolve(Type serviceType, out object instance)
        {
            return container.TryResolve(serviceType, out instance);
        }


        public object ResolveUnregistered(Type type)
        {
            return Activator.CreateInstance(type, null);
            
        }
    }
}